﻿using Common.Communication;
using DeviceBase.Interfaces;
using DeviceBase.Models;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CaiJi.Core.DianZu
{
    public class AT512SerialPort : SerialPortBase, ICaiJi
    {
        public AT512SerialPort(string portName, int baudRate = 115200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One, int timeout = 1000) : base(portName, baudRate, parity, dataBits, stopBits, timeout)
        {
        }

        public string Name { get; set; }

        public Result<List<ChuanGanQiResult>> GetValue()
        {
            Result<List<ChuanGanQiResult>> result = new Result<List<ChuanGanQiResult>>();
            AppendInfo(Name, $"设置自动量程");
            var re = Write(CmdAutoRange);
            if (re.IsSucceed == false)
            {
                result.IsSucceed = false;
                result.Err = "设置自动量程失败";
                AppendResult(Name, result.Err);
                return result.EndTime();
            }
            var re1 = WriteThenRead(CmdGetRange);
            if (re.IsSucceed == false || !re1.Value.Contains("AUTO"))
            {
                result.IsSucceed = false;
                result.Err = "设置自动量程失败";
                AppendResult(Name, result.Err);
                return result.EndTime();
            }
            AppendInfo(Name, $"读取当前电压值");
            re1 = WriteThenRead(CmdFetch);
            if (re1.IsSucceed == false || !double.TryParse(re1.Value,out double R))
            {
                result.IsSucceed = false;
                result.Err = "读取当前电压值失败";
                AppendResult(Name, result.Err);
                return result.EndTime();
            }
            result.Value.Add(new ChuanGanQiResult() { channel = 1, value = R, result = R.ToString("F3") + "Ω" });
            foreach (var item in result.Value)
            {
                AppendInfo(Name, item.result);
            }
            return result.EndTime();
        }

        public Result<bool> SetParameter(params int[] value)
        {
            Result<bool> result = new Result<bool>();
            result.IsSucceed = false;
            result.Err = "暂不支持";
            AppendResult(Name, result.Err);
            return result.EndTime();
        }

        string CmdFetch => "FETCH?\n";
        string CmdAutoRange => "FUNC:RANG: AUTO ON\n";
        string CmdGetRange => "FUNC:RANG?\n";
    }
}
